import xlwt



def Xlwt_Export(Tab_Data, Tab_Name, Sav_Path):
    """
    :param Tab_Data: 数据库查询出来的对象
    :param Tab_Name: 导出的表名称
    :param Sav_Path: 导出的excel绝对路径
    :return:
    """
    try:
        DATA_title = list(Tab_Data[0].keys())
        Line_len = len(Tab_Data)
        Col_len = len(DATA_title)
        Excel_obj = xlwt.Workbook(encoding='utf-8')
        Excel_tab = Excel_obj.add_sheet(Tab_Name)
        for T in range(0, Col_len):
            Excel_tab.write(0, T, DATA_title[T])
        for C in range(0, Line_len):
            DATA_line = dict(Tab_Data[C])
            for L in range(0, Col_len):
                DATA_field = DATA_title[L]
                DATA_value = DATA_line.get(DATA_field)
                Excel_tab.write(C + 1, L, DATA_value)
        Excel_obj.save(Sav_Path)
    except Exception  as e:
        pass


# import pymysql, xlwt
#
#
# def Xlwt_Export(table_name):
#     # 连接数据库，查询数据
#     host, user, passwd, db = '127.0.0.1', 'root', '5201314a', 'vue_admin'
#     conn = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8')
#     cur = conn.cursor()
#     sql = 'select * from %s' % table_name
#     cur.execute(sql)  # 返回受影响的行数
#
#     fields = [field[0] for field in cur.description]  # 获取所有字段名
#     all_data = cur.fetchall()  # 所有数据
#
#     # 写入excel
#     book = xlwt.Workbook()
#     sheet = book.add_sheet('sheet1')
#
#     for col, field in enumerate(fields):
#         sheet.write(0, col, field)
#
#     row = 1
#     for data in all_data:
#         for col, field in enumerate(data):
#             sheet.write(row, col, field)
#         row += 1
#     book.save("%s.xls" % table_name)

